import sys
import logging
import util.dtest
import test.utils
import test.neon_support as ns

print '''
XXX/bowei -- need to add asserts to make sure the data was transfered
Test of 2 nodes, syncing some amount of faked data.
'''

dtest = util.dtest.DTest()
cond = ns.Conditions(dtest)

node_a = dtest.add_node(ns.NeonNode('A'))
node_b = dtest.add_node(ns.NeonNode('B'))

# Create link between A <-> B
node_a_in = node_a.reg_tx_tcp_in()
node_b.reg_tx_tcp_out(node_a_in, 1)

# setup file
types = '''# type file
def config(atom_store):
    t = AtomType('test')
    t.add_table('test', ('SELECT guid FROM test WHERE i = ?', 'i'))
    atom_store.reg_type(t)
'''

node_a.reg_dynfile('test.types', types)
node_b.reg_dynfile('test.types', types)

dtest.set_mapper(util.dtest.LocalMapper())

dtest.configure()
dtest.setup_files()

def ins_fake_entry(n, i):
    q = '''
    INSERT INTO test VALUES ('A:%d', %d);
    INSERT INTO neon_atom_meta VALUES ('A:%d', 'A:%d', 'test', 0, 1);
    ''' % (i, i, i, i)
    n.host().run_cmd_2('sqlite3', 'neon.db', q)

def test_script(tr):
    node_a.run_tx()
    node_b.run_tx()
    
    tr.wait_for(5, cond.on_all(cond.tx_is_running))
    tr.wait_for(5, cond.channel_state, 'A', 'tcp/0', 'B', 'handshake')
    tr.wait_for(5, cond.channel_state, 'B', 'tcp/0', 'A', 'handshake')

    # setup databases and tables
    env = {'NEON_TYPE_FILE' : 'test.types'}
    node_a.run_sync_init(None, env)
    node_b.run_sync_init(None, env)
    node_a.host().run_cmd_2('sqlite3', 'neon.db', 'CREATE TABLE test (guid, i);')
    node_b.host().run_cmd_2('sqlite3', 'neon.db', 'CREATE TABLE test (guid, i);')

    node_a.run_sync(None, env)
    node_b.run_sync(None, env)

    tr.sleep(2)

    for i in xrange(5):
	ins_fake_entry(node_a, i)
    tr.pause()

    node_a.host().run_cmd_2('sqlite3', 'neon.db',
                            '''begin; select * from neon_atom_meta; end;''')
    node_b.host().run_cmd_2('sqlite3', 'neon.db',
                            '''begin; select * from neon_atom_meta; end;''')
    tr.pause()
        
dtest.run(test_script)
